package com.example.onlinemarket.fragment;

import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.onlinemarket.Application;
import com.example.onlinemarket.R;
import com.example.onlinemarket.activity.ImgUpdateActivity;
import com.example.onlinemarket.activity.MainActivity;
import com.example.onlinemarket.graphics.UpdatePwdDialog;
import com.example.onlinemarket.util.ActivityUtil;
import com.mock.alipay.Callback;
import com.mock.alipay.PasswordKeypad;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.example.onlinemarket.Application.loginUser;
import static com.example.onlinemarket.Application.showProgressDialog;
import static com.example.onlinemarket.util.DialogUtil.getUpdateAddressDialog;
import static com.example.onlinemarket.util.DialogUtil.getUpdateEmailDialog;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;

public class UserFragment extends Fragment {

    private CircleImageView userImg;
    private TextView userNameTv;
    private TextView roleTv;
    private TextView pwdTv;
    private TextView payPwdTv;
    private ConstraintLayout emailLayout;
    private TextView emailTv;
    private ConstraintLayout addressLayout;
    private TextView addressTv;
    private TextView logoutTv;
    private TextView exitTv;
    private RefreshListener refreshListener;

    private PasswordKeypad keypad;
    private AtomicBoolean isOrigin = new AtomicBoolean(false);
    private AtomicBoolean isConfirm = new AtomicBoolean(false);
    private AtomicReference<String> pwd = new AtomicReference<>();

    public UserFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        //初始化组件
        initWidgets(view);
        //为组件设置监听器
        setWidgetsListener();
        return view;
    }

    //为组件设置监听器
    private void setWidgetsListener() {
        userImg.setOnClickListener(v -> {
            showProgressDialog(getContext());
            ActivityUtil.jumpToActivityForResult(ImgUpdateActivity.class, 0);
        });
        pwdTv.setOnClickListener(v -> UpdatePwdDialog.newInstance(Objects.requireNonNull(getContext())).show());
        logoutTv.setOnClickListener(v -> logout());
        exitTv.setOnClickListener(v -> ActivityUtil.removeAll());
        refreshListener = new RefreshListener() {
            @Override
            public void refreshEmail() {
                emailTv.setText(loginUser.getEmail());
                Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void refreshAddress() {
                addressTv.setText(loginUser.getAddress());
                Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
            }
        };
        emailLayout.setOnClickListener(v -> getUpdateEmailDialog(Objects.requireNonNull(getContext()), refreshListener).show());
        addressLayout.setOnClickListener(v -> getUpdateAddressDialog(Objects.requireNonNull(getContext()), refreshListener).show());
        payPwdTv.setOnClickListener(v -> {
            keypad = getKeyPad("请输入原交易密码");
            keypad.show(getFragmentManager(), "PasswordKeypad");
        });
    }

    private PasswordKeypad getKeyPad(String title){
        PasswordKeypad passwordKeypad = new PasswordKeypad(title);
        passwordKeypad.setPasswordCount(6);
        passwordKeypad.setCancelable(false);
        passwordKeypad.setCallback(new Callback() {
            @Override
            public void onForgetPassword() {
                Toast.makeText(getContext(), "忘记密码",Toast.LENGTH_LONG).show();
            }
            @Override
            public void onInputCompleted(CharSequence password) {
                new Handler().postDelayed(() -> {
                    if(!isOrigin.get()){
                        if(password.toString().equals(loginUser.getPayPassword())){
                            isOrigin.set(true);
                            passwordKeypad.dismiss();
                            keypad = getKeyPad("请输入新支付密码");
                            keypad.show(getFragmentManager(), "PasswordKeypad");
                        }else{
                            passwordKeypad.setPasswordState(false, "密码验证错误");
                        }
                    }else{
                        if(!isConfirm.get()){
                            if(password.toString().equals(loginUser.getPayPassword())){
                                Toast.makeText(getContext(), "新旧密码不能相同", Toast.LENGTH_SHORT).show();
                                passwordKeypad.setPasswordState(false, "新旧密码不能相同");
                            }else{
                                isConfirm.set(true);
                                pwd.set(password.toString());
                                passwordKeypad.dismiss();
                                keypad = getKeyPad("请再次确认支付密码");
                                keypad.show(getFragmentManager(), "PasswordKeypad");
                            }
                        }else{
                            if(password.toString().equals(pwd.get())){
                                updatePayPassword();
                            }else{
                                passwordKeypad.setPasswordState(false, "两次输入的密码不相同");
                            }
                        }
                    }
                },1000);
            }

            @Override
            public void onPasswordCorrectly() {
                passwordKeypad.dismiss();
            }

            @Override
            public void onCancel() {
                passwordKeypad.dismiss();
                isConfirm.set(false);
                isOrigin.set(false);
                Toast.makeText(getContext(), "取消了修改支付密码", Toast.LENGTH_SHORT).show();
            }
        });
        return passwordKeypad;
    }

    private void updatePayPassword(){
        new Thread(() -> {
            Map<String, String> map = new HashMap<>();
            map.put("userId", String.valueOf(loginUser.getUserId()));
            map.put("payPassword", pwd.get());
            String response = sendHttpRequest("/updatePayPassword", "POST", map);
            isConfirm.set(false);
            isOrigin.set(false);
            if(response!=null&&!response.isEmpty()){
                Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
                    if(response.equals("true")){
                        Toast.makeText(getContext(), "交易密码设置完成", Toast.LENGTH_SHORT).show();
                        loginUser.setPayPassword(pwd.get());
                        keypad.setPasswordState(true);
                    }else{
                        Toast.makeText(getContext(), "交易密码设置失败", Toast.LENGTH_SHORT).show();
                        keypad.dismiss();
                    }
                });
            }
        }).start();
    }

    public interface RefreshListener{
        void refreshEmail();
        void refreshAddress();
    }

    //注销账号
    private void logout(){
        Application.isLogout = true;
        Objects.requireNonNull(getActivity()).finish();
    }

    //初始化组件
    private void initWidgets(View view){
        userImg = view.findViewById(R.id.iv_user_info_img);
        userNameTv = view.findViewById(R.id.tv_user_info_user_name);
        roleTv = view.findViewById(R.id.tv_user_info_role);
        pwdTv = view.findViewById(R.id.tv_user_info_update_password);
        payPwdTv = view.findViewById(R.id.tv_user_info_update_pay_password);
        emailTv = view.findViewById(R.id.tv_user_info_email);
        emailLayout = view.findViewById(R.id.layout_email);
        addressTv = view.findViewById(R.id.tv_user_info_address);
        addressLayout = view.findViewById(R.id.layout_address);
        logoutTv = view.findViewById(R.id.tv_user_info_logout);
        exitTv = view.findViewById(R.id.tv_user_info_exit);

        userNameTv.setText(loginUser.getUserName());
        roleTv.setText(loginUser.isRole()?"卖家":"买家");
        emailTv.setText(loginUser.getEmail());
        addressTv.setText(loginUser.getAddress());
        setUserImg();
    }

    //设置用户头像
    public void setUserImg() {
        Glide.with(UserFragment.this)
                .load(loginUser.getLocalPath())
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .override(550, 550).placeholder(R.drawable.ic_no_img).into(userImg);
    }
}